package com.za.plugin.transfer.func;


import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

// 达梦不支持 count(true) , count(null) , count(false) 等写法
public class CountFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {

        return clearSpace(sql).contains("count(");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("count\\s*\\(", "count(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains("count(")) {
            int idx = sql.indexOf("count(");
            StringBuilder sb = new StringBuilder();
            int left = 0;
            while (idx >= 0) {
                Content expectContent = StrUtil.getExpectContent(sql, idx + 5);
                assert expectContent != null;
                String expectStr = expectContent.getExpectStr();
                int end = expectContent.getEnd();
                expectStr = expectStr.replaceAll("\\s+", " ");
                expectStr = expectStr.replaceAll("then true", "then 1");
                expectStr = expectStr.replaceAll("then false", "then 0");
                expectStr = expectStr.replaceAll("else true", "else 1");
                expectStr = expectStr.replaceAll("else false", "else 0");
                expectStr = expectStr.replaceAll("then null", "then 0");
                expectStr = expectStr.replaceAll("else null", "else 0");
                sb.append(sql, left, idx + 6).append(expectStr).append(")");
                idx = sql.indexOf("count(", idx + 6);
                if (idx == -1) {
                    sb.append(sql.substring(end));
                }
                left = end;
            }
            sql = sb.toString();
        }
        return sql;
    }
}
